<%@page import="java.util.UUID"%>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@ include file="/WEB-INF/pages/common/taglib.jsp" %>
<%
    String uuid = UUID.randomUUID().toString();
    request.setAttribute("uuid", uuid);
%>

<div class="row" >
	<div class="col-md-3">
		<div class="box box-primary">
			<div class="box-header with-border">
				<h3 class="box-title">
    			
    			</h3>
    			<div class="box-tools pull-right" id="dataDicAttrTreeTool_${uuid}">
    				<shiro:hasPermission name="DATADIC_ATTR_ADD">
	                <a href="javascript:void(0)" class="btn btn-sm btn-success addBt">
	                   <span class="glyphicon glyphicon-plus" aria-hidden="true"></span>  添加
	                </a>
	                </shiro:hasPermission>
	                
	                <shiro:hasPermission name="DATADIC_ATTR_MOD">
	                <a href="javascript:void(0)" class="btn btn-sm btn-primary editBt">
	                    <span class="glyphicon glyphicon-edit" aria-hidden="true"></span> 修改
	                </a>
	                </shiro:hasPermission>
	                
	                <shiro:hasPermission name="DATADIC_ATTR_DEL">
	                <a href="javascript:void(0)" class="btn btn-sm btn-danger delBt">
	                    <span class="glyphicon glyphicon-trash" aria-hidden="true"></span> 删除
	                </a>
	                </shiro:hasPermission>
    			</div>
			</div>
			<div class="box-body">
				<div id="dataDicAttrTree_${uuid}"  class="ztree am-margin">

        		</div>
			</div>
		</div>
	</div>
    <div class="col-md-5">
    	<div class="box box-primary">
			<div class="box-header with-border">
				<h3 class="box-title">
    			
    			</h3>
    			<div class="box-tools pull-right" id="dataDicGridTB_${uuid}">
    				<shiro:hasPermission name="DATADIC_ADD">
		    		<button class="btn btn-sm btn-success addBtn">
		    			<span class="glyphicon glyphicon-plus" aria-hidden="true"></span> 添加
		    		</button>
		    		</shiro:hasPermission>
		    		
		    		<shiro:hasPermission name="DATADIC_MOD">
		    		<button class="btn btn-sm btn-primary editBtn">
		    			<span class="glyphicon glyphicon-pencil" aria-hidden="true"></span> 修改
		    		</button>
		    		</shiro:hasPermission>
		    		
		    		<shiro:hasPermission name="DATADIC_DEL">
		    		<button class="btn btn-sm btn-danger delBtn">
		    			<span class="glyphicon glyphicon-trash" aria-hidden="true"></span> 删除
		    		</button>
		    		</shiro:hasPermission>
		    		
		    		<shiro:hasPermission name="DATADIC_MOD">
		    		<div class="btn-group">
					  <button type="button" class="btn btn-sm btn-default dropdown-toggle" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
					   	 交换 <span class="caret"></span>
					  </button>
					  <ul class="dropdown-menu">
					    <li><a href="javascript:void(0)" class="expBtn">导出</a></li>
					    <li><a href="javascript:void(0)" class="impBtn" id="impDataDicBtn">导入</a></li>
					  </ul>
					</div>
					</shiro:hasPermission>
					
    			</div>
			</div>
			<div class="box-body">
				<table id="dataDicGrid_${uuid}" >

        		</table>
			</div>
		</div>        
    </div>
    <div class="col-md-4">
    	<div class="box box-primary">
			<div class="box-header with-border">
				<h3 class="box-title">
    			
    			</h3>
    			<div class="box-tools pull-right" id="dataDicItemTreeTool_${uuid}">
    				<shiro:hasPermission name="DATADIC_ITEM_ADD">
	                <a href="javascript:void(0)" class="btn btn-sm btn-success addBt">
	                   <span class="glyphicon glyphicon-plus" aria-hidden="true"></span>  添加
	                </a>
	                </shiro:hasPermission>
	                
	                <shiro:hasPermission name="DATADIC_ITEM_MOD">
	                <a href="javascript:void(0)" class="btn btn-sm btn-primary editBt">
	                    <span class="glyphicon glyphicon-edit" aria-hidden="true"></span> 修改
	                </a>
	                </shiro:hasPermission>
	                
	                <shiro:hasPermission name="DATADIC_ITEM_DEL">
	                <a href="javascript:void(0)" class="btn btn-sm btn-danger delBt">
	                    <span class="glyphicon glyphicon-trash" aria-hidden="true"></span> 删除
	                </a>
	                </shiro:hasPermission>
	                
	                <shiro:hasPermission name="DATADIC_ITEM_MOD">
		    		<button class="btn btn-sm btn-primary orgRelBtn">
		    			<span class="glyphicon glyphicon-pencil" aria-hidden="true"></span> 关联机构
		    		</button>
		    		</shiro:hasPermission>
    			</div>
			</div>
			<div class="box-body">
				<div id="dataDicItemTree_${uuid}"  class="ztree am-margin">

        		</div>
			</div>
		</div>
    </div>
</div>

<script type="text/javascript">
    $(function () {
        var uuid = '${uuid}';
        var dataDicId;
        
        var dataDicGrid = $("#dataDicGrid_"+uuid);
        var dataDicGridTB= $("#dataDicGridTB_"+uuid);
        var dataDicItemTree = $("#dataDicItemTree_"+uuid);
        var dataDicItemTreeTool = $("#dataDicItemTreeTool_"+uuid);
        var dataDicAttrTree=$("#dataDicAttrTree_"+uuid);
		var dataDicAttrTreeTool=$("#dataDicAttrTreeTool_"+uuid);
        
        dataDicAttrTree = $.fn.zTree.init(dataDicAttrTree, {
            treeId: "dataDicAttrTree",
            async: {
                enable: true,
                url: ctx + "/dataDicAction/queryDataDicItemTreeNodes.do",
                autoParam: ["id=pid"],
                otherParam: {"dataDicCode":"DATADIC_ATTR"},
                dataFilter: function (treeId, parentNode, responseData) {
                    if (responseData) {
                        $.each(responseData, function (i, n) {
                            if (n.childrenSize > 0) {
                                n.isParent = true;
                            }
                        });
                    }
                    return responseData;
                }
            },
            data: {
                key: {
                    name: "text"
                }
            },
            edit: {
                enable: true,
                showRemoveBtn: false,
                showRenameBtn: false,
                drag: {
                    isCopy: false
                }
            },
            callback: {
                onDrop: function (e, treeId, treeNodes, targetNode, moveType, isCopy) {
                	if (treeNodes && treeNodes.length > 0) {
                        var treeNode = treeNodes[0];
                        var pNode = dataDicAttrTree.getNodeByTId(treeNode.parentTId);
                        var ids = [];
                        $.each(pNode.children, function (i, n) {
                            ids.push(n.id);
                        });
                        $.post(ctx + "/dataDicAction/seqNodes.do", {ids: ids.join(","), pid: pNode.id}, function (data) {
                            if (data.success) {
                            } else {
                                webUtils.error(data.msg);
                            }
                        }, "json");
                    }
                },
                onClick: function (e, treeId, treeNode, clickFlag) {
                    if (clickFlag != 0) {
                    	dataDicGrid.dataDicAttr = treeNode.value;
                    	dataDicGrid.bootstrapTable("refresh");
                    }
                }
            }
        }, [{
                text: "字典分类",
                id: "-1",
                isParent: true,
                open: true
            }]);
        
        dataDicAttrTree.reAsyncChildNodes(dataDicAttrTree.getNodesByParam("id", "-1")[0], "refresh");
        
        
        dataDicAttrTreeTool.find(".addBt").click(function(){
        	
        	var nodes = dataDicAttrTree.getSelectedNodes();
        	var pid = '-1';
        	if (nodes && nodes.length > 0) {
        		var node = nodes[0];
        		pid = node.id;
        		
        		var sub = top.webUtils.topicSubscribe("dataDicAttr.edit.success", function (args) {
        			var cnode = args.obj;
        			dataDicAttrTree.addNodes(node, cnode);
                    dialog.close();
                },true);
        		
        		var dialog = editDataDicAttr({
                	pid: pid,
                    onClose: function () {
                        sub.remove();
                    }
                });
        	}else {
            	webUtils.alert("请选择其中一个");
            }
            
        });
        
		dataDicAttrTreeTool.find(".editBt").click(function(){
			var nodes = dataDicAttrTree.getSelectedNodes();
            if (nodes && nodes.length > 0) {
            	var node = nodes[0];
                var sub = top.webUtils.topicSubscribe("dataDicAttr.edit.success", function (args) {
                    var cnode = args.obj;
                    dataDicAttrTree.updateNode($.extend(node, cnode));
                    dialog.close();
                },true);                
                var dialog = editDataDicAttr({
                    id: node.id,
                    onClose: function () {
                        sub.remove();
                    }
                });
            }else {
            	webUtils.alert("请选择其中一个");
            }
        });
		
		dataDicAttrTreeTool.find(".delBt").click(function(){
			var nodes = dataDicAttrTree.getSelectedNodes();
            if (nodes && nodes.length > 0) {
            	webUtils.confirm("删除后将不可恢复，请问是否继续?", function(result) {
					if(result){
						var node = nodes[0];
		                var ids = [];
		                ids.push(node.id);
		                $.post(ctx + "/dataDicAction/delDataDicItems.do", {ids: ids.join(",")}, function (data) {
		                    if (data.success) {
		                    	dataDicAttrTree.removeNode(node);
		                    } else {
		                    	webUtils.error(data.msg);
		                    }
		                }, 'json');
					}
        		});
            } else {
            	webUtils.alert("请选择需要删除的");
            }
        });
		
		function editDataDicAttr(params){
			params = params || {};
            var t = [];
            if (params.id) {
                t.push("id=" + params.id);
            }
            if (params.pid) {
                t.push("pid=" + params.pid);
            }
            t.push("dataDicCode=DATADIC_ATTR");
            var dialog=webUtils.dialog({
           	 title:'编辑字典类型',
           	 url:ctx + '/dataDicAction/dataDicAttrEditView.do?' + t.join("&"),
           	 onremove:function () {
                    if (params.onClose) {
                        params.onClose.call(null);
                    }
                }
            });
            return dialog;
		}
        

        var editRowData = {};
        dataDicGrid = dataDicGrid.bootstrapTable({
        	url:ctx + "/dataDicAction/queryDataDics.do",
        	filterControl:true,
        	queryParams:function(d){
				if(dataDicGrid && dataDicGrid.dataDicAttr){
	    			d.dataDicAttr=dataDicGrid.dataDicAttr;
	    		}
				return d;
			},
            columns: [
					{field: '_id',checkbox:true},
                    {title: '字典名称',field: 'name',filterControl:"input"},
                    {title: '编码',field: 'code',filterControl:"input"}
                ],
           onClickRow:function(row){
                	dataDicId = row.id;
                    dataDicItemTree.dataDicId = dataDicId;
                    dataDicItemTree.setting.async.otherParam.dataDicId = dataDicId;
                    dataDicItemTree.reAsyncChildNodes(dataDicItemTree.getNodesByParam("id", "-1")[0], "refresh");
                }
        });
        
        dataDicGridTB.find(".addBtn").click(function(){
        	var sub = top.webUtils.topicSubscribe("dataDic.edit.success", function (args) {
                dialog.close();
                dataDicGrid.bootstrapTable("refresh");
            });
        	var nodes = dataDicAttrTree.getSelectedNodes();
        	var dataDicAttr;
        	if (nodes && nodes.length > 0) {
        		var node = nodes[0];
        		dataDicAttr=node.value;
        	}
            var dialog = editDataDic({
            	dicAttr:dataDicAttr,
                onClose: function () {
                    sub.remove();
                }
            });
        });
        
        dataDicGridTB.find(".editBtn").click(function(){
        	var rows=dataDicGrid.bootstrapTable("getSelections");
        	if(rows && rows.length>0){
        		var sub = top.webUtils.topicSubscribe("dataDic.edit.success", function (args) {
            		dialog.close();
            		dataDicGrid.bootstrapTable("refresh");
                },true);
        		var row=rows[0];
        		var dialog= editDataDic({
                	id:row.id,
                    onClose: function () {
                        sub.remove();
                    }
                });
        	} else {
        		webUtils.alert("请选择需要编辑的数据");
            }
        });
        
        dataDicGridTB.find(".delBtn").click(function(){
        	var rows=dataDicGrid.bootstrapTable("getSelections");
        	if(rows && rows.length>0){
        		webUtils.confirm("删除后将不可恢复，请问是否继续?", function(result) {
					if(result){
						var selecteds = [];
		                $.each(rows, function (i, n) {
		                    selecteds.push(n.id);
		                });
		                $.post(ctx + "/dataDicAction/delDataDics.do", {
		                    ids: selecteds.join(",")
		                }, function (data) {
		                    if (data.success) {
		                    	dataDicGrid.bootstrapTable("refresh");
		                    } else {
		                    	webUtils.alert(data.msg);
		                    }
		                }, 'json');
					}
        		});
        		
        	} else {
        		webUtils.alert("请选择需要删除的数据");
            }
            
        });
        
        dataDicGridTB.find(".expBtn").click(function(){
        	var rows=dataDicGrid.bootstrapTable("getSelections");
        	if(rows && rows.length>0){
        		var ids = [];
                $.each(rows, function (i, n) {
                	ids.push(n.id);
                });
        		window.open(ctx + "/dataDicAction/export.do?ids="+ids.join(","));
        	} else {
        		webUtils.alert("请选择需要导出的数据");
            }
        });
        
        var uploader
        webUtils.fileUploader({
        	server:ctx+"/dataDicAction/import.do",
        	uploadPick:"#impDataDicBtn",
        	duplicate:false,
        	accept: {
                title: 'json文件类型',
                //需要与platform.upload.allowFileTypes配置保持一致
                extensions: 'json'
            },
            afterInit:function(u,uder){
            	uploader=u;
            }
        });
        
        dataDicGridTB.find(".impBtn").mouseenter(function(){
        	uploader.refresh();
        });
        
        
        function editDataDic(params){
        	 params = params || {};
             var t = [];
             if (params.id) {
                 t.push("id=" + params.id);
             }
             if(params.dicAttr){
            	 t.push("dicAttr=" + params.dicAttr);
             }
             //取得字典值
             var dialog=webUtils.dialog({
            	 title:'编辑数据字典',
            	 url:ctx + '/dataDicAction/dataDicEditView.do?' + t.join("&"),
            	 onremove:function () {
                     if (params.onClose) {
                         params.onClose.call(null);
                     }
                 }
             });
             return dialog;
        }
        
        
        
        dataDicItemTree = $.fn.zTree.init(dataDicItemTree, {
            treeId: "dataDicItemTree",
            async: {
                enable: true,
                url: ctx + "/dataDicAction/queryDataDicItemTreeNodes.do",
                autoParam: ["id=pid"],
                otherParam: {},
                dataFilter: function (treeId, parentNode, responseData) {
                    if (responseData) {
                        $.each(responseData, function (i, n) {
                            if (n.childrenSize > 0) {
                                n.isParent = true;
                            }
                        });
                    }
                    return responseData;
                }
            },
            data: {
                key: {
                    name: "text"
                }
            },
            edit: {
                enable: true,
                showRemoveBtn: false,
                showRenameBtn: false,
                drag: {
                    isCopy: false
                }
            },
            callback: {
                beforeAsync: function (treeId, treeNode) {
                    return !!dataDicItemTree.dataDicId;
                },
                onDrop: function (e, treeId, treeNodes, targetNode, moveType, isCopy) {
                    if (treeNodes && treeNodes.length > 0) {
                        var treeNode = treeNodes[0];
                        var pNode = dataDicItemTree.getNodeByTId(treeNode.parentTId);
                        var ids = [];
                        $.each(pNode.children, function (i, n) {
                            ids.push(n.id);
                        });
                        $.post(ctx + "/dataDicAction/seqNodes.do", {ids: ids.join(","), pid: pNode.id}, function (data) {
                            if (data.success) {
                            } else {
                                webUtils.error(data.msg);
                            }
                        }, "json");
                    }
                }
            }
        }, [{
                text: "数据字典",
                id: "-1",
                isParent: true,
                open: true
            }]);

        var editDataDicItem = function (params) {
            params = params || {};
            var t = [];
            if (params.id) {
                t.push("id=" + params.id);
            }
            if (params.pid) {
                t.push("pid=" + params.pid);
            }
            if (params.dataDicId) {
                t.push("dataDicId=" + params.dataDicId);
            }
            
            var dialog=webUtils.dialog({
           	 title:'编辑字典项',
           	 url:ctx + '/dataDicAction/dataDicItemEditView.do?' + t.join("&"),
           	 onremove:function () {
                    if (params.onClose) {
                        params.onClose.call(null);
                    }
                }
            });
            return dialog;
        };

        dataDicItemTreeTool.find(".addBt").click(function () {
            if (!dataDicId) {
            	webUtils.alert("请选择具体的字典");
                return;
            }

            var nodes = dataDicItemTree.getSelectedNodes();
            var pid = '-1';
            if (nodes && nodes.length > 0) {
                var node = nodes[0];
                pid = node.id;

                var sub = top.webUtils.topicSubscribe("dataDicItem.edit.success", function (args) {
                    var cnode = args.obj;
                    dataDicItemTree.addNodes(node, cnode);
                    dialog.close();
                },true);
                var dialog = editDataDicItem({
                    pid: pid,
                    dataDicId: dataDicId,
                    onClose: function () {
                        sub.remove();
                    }
                });
            }

        });

        dataDicItemTreeTool.find(".editBt").click(function () {
            var nodes = dataDicItemTree.getSelectedNodes();
            if (nodes && nodes.length > 0) {
                var node = nodes[0];
                var sub = top.webUtils.topicSubscribe("dataDicItem.edit.success", function (args) {
                    var cnode = args.obj;
                    dataDicItemTree.updateNode($.extend(node, cnode));
                    dialog.close();
                });                
                var dialog = editDataDicItem({
                    id: node.id,
                    onClose: function () {
                        sub.remove();
                    }
                });
            } else {
            	webUtils.alert("请选择其中一个");
            }
        });

        dataDicItemTreeTool.find(".delBt").click(function () {
            var nodes = dataDicItemTree.getSelectedNodes();
            if (nodes && nodes.length > 0) {
            	webUtils.confirm("删除后将不可恢复，请问是否继续?", function(result) {
					if(result){
						var node = nodes[0];
		                var ids = [];
		                ids.push(node.id);
		                $.post(ctx + "/dataDicAction/delDataDicItems.do", {ids: ids.join(",")}, function (data) {
		                    if (data.success) {
		                        dataDicItemTree.removeNode(node);
		                    } else {
		                    	webUtils.error(data.msg);
		                    }
		                }, 'json');
					}
        		});
            } else {
            	webUtils.alert("请选择需要删除的");
            }
        });
        
        dataDicItemTreeTool.find(".orgRelBtn").click(function () {
        	var nodes = dataDicItemTree.getSelectedNodes();
            if (nodes && nodes.length > 0) {
            	var node = nodes[0];
            	$.getJSON(ctx+"/dataDicAction/loadItemOrgs.do",{
            		id:node.id
            	},function(data){
            		webUtils.orgSelector({
            			hasSelectedOrgs:data,
            			onSelect:function(ds){
            				var orgIds=[];
            				$.each(ds,function(i,n){
            					orgIds.push(n.id);
            				});
            				$.post(ctx+"/dataDicAction/saveDataDicItemOrgByOrgIds.do",{
        						id:node.id,orgIds:orgIds.join(",")
        					},function(r){
        						if (r.success) {
        							webUtils.alert("保存成功");
    		                    } else {
    		                    	webUtils.error(data.msg);
    		                    }
        					},"json");
            			}
            		});
            	});
            } else {
            	webUtils.alert("请选择其中一个");
            }
        });
        

    });


</script>